package com.nulldev.util.security.encryptAPI.impls.a51;

import com.nulldev.util.VariableAPI.StringsUtil;
import com.nulldev.util.security.encryptAPI.Encryptor;

public class A51 extends Encryptor {
	private final String key;
	private final A51Cipher cipher;

	public A51(final String key) {
		super("encryptapi.tp.a51", new String[]
			{ "A51", "A5/1" }, key);
		this.key = key;
		final String k = StringsUtil.toBinary(key);
		if (k.length() > 64) {
			this.cipher = new A51Cipher(k.substring(0, 64));
		} else
			this.cipher = new A51Cipher(k);
	}

	public A51(final byte[] key) {
		super("encryptapi.tp.a51", new String[]
			{ "A51", "A5/1" }, key);
		this.key = new String(key);
		this.cipher = new A51Cipher(StringsUtil.toBinary(new String(key)));
	}

	@Override
	public byte[] getKey() {
		return this.key.getBytes();
	}

	@Override
	public byte[] encryptToBytes(Object o) {
		if (o instanceof byte[]) {
			return this.cipher.encrypt(new String((byte[]) o)).getBytes();
		} else if (o instanceof String) {
			return this.cipher.encrypt((String) o).getBytes();
		} else {
			throw new UnsupportedOperationException("encryptToBytes() -> Unsupported operation on: " + o);
		}
	}

	@Override
	public String encrypt(Object o) {
		if (o instanceof byte[]) {
			return this.cipher.encrypt(new String((byte[]) o));
		} else if (o instanceof String) {
			return this.cipher.encrypt(((String) o));
		} else {
			throw new UnsupportedOperationException("encryptToBytes() -> Unsupported operation on: " + o);
		}
	}

	@Override
	public byte[] decryptToBytes(byte[] b) {
		return this.cipher.decrypt(new String(b)).getBytes();
	}

	@Override
	public String decrypt(String s) {
		return this.cipher.decrypt(s);
	}

	@Override
	public String getKeyAsString() {
		return this.key;
	}
}
